﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Model;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using MainApp.Helper;
using BLL;
using View;
using System.Threading;

namespace MainApp.Forms
{
    public partial class FormRelation : XtraForm, IChildForm
    {
        List<Relation> professionList = new List<Relation>();
        DataContext context = new DataContext();

        public FormRelation()
        {
            InitializeComponent();
        }

        private void FormCateogory_Load(object sender, EventArgs e)
        {
            loadData();
        }

        private void loadData()
        {
            professionList.Clear();
            professionList.AddRange(context.DataRepertory.Relations.ToList());
            this.entityViewBindingSource.DataSource = professionList;
        }

        public OperationResult Save()
        {
            this.gridView1.CloseEditor();
            List<Relation> updateList = new List<Relation>();
            List<Relation> addList = new List<Relation>();
            professionList.ForEach(w =>
            {
                if (w.ID == 0)
                {
                    addList.Add(w);
                }
                else
                {
                    updateList.Add(w);
                }
            });

            context.Update<Relation>(updateList);
            context.Insert<Relation>(addList);
            context.SaveChanges();
            return new OperationResult { Success = true };
        }

        public OperationResult Delete()
        {
            var indexs = this.gridView1.GetSelectedRows();
            List<Relation> deleteList = new List<Relation>();
            foreach (int i in indexs)
            {
                deleteList.Add(professionList[this.gridView1.GetDataSourceRowIndex(i)]);
            }

            return context.DeleteRelations(deleteList);
        }

        public OperationResult RefreshData()
        {
            loadData();
            this.gridControl1.RefreshDataSource();
            return new OperationResult(true);
        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            Relation view = e.Row as Relation;
            if (string.IsNullOrEmpty(view.Name))
            {
                e.Valid = false; e.ErrorText += "名称不能为空！"; return;
            }
            else
            {
                if (view.Name.Length > 50)
                {
                    e.Valid = false; e.ErrorText += "名称长度不能超过50！"; return;
                }
            }

            e.Valid = true;
        }
    }
}
